package com.tjvib.view.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.tjvib.R;
import com.tjvib.adapter.DeviceAdapter;
import com.tjvib.base.BaseActivity;
import com.tjvib.bean.SensorInfo;
import com.tjvib.common.Callback;
import com.tjvib.event.ScanStatusEvent;
import com.tjvib.permission.PermissionListener;
import com.tjvib.permission.PermissionRequest;
import com.tjvib.presenter.ZeroLabDevicePresenter;
import com.tjvib.util.LogUtil;
import com.tjvib.util.Manager.AppManager;
import com.tjvib.util.PressUtil;
import com.tjvib.util.ToastUtil;
import com.tjvib.view.dialog.HintDialog;
import com.tjvib.view.dialog.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * BLE开发
 */
public class ZeroLabDeviceActivity extends BaseActivity<ZeroLabDevicePresenter>
        implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = "ZLDeviceActivity";

    private String[] perms = new String[]{};
    private static final int ACTION_REQUEST_ENABLE = 355;
    private static final int APP_SETTINGS_REQ_CODE = 16061;
    private int RC_PERMISSION = 2;


    // bt_patch(mtu).bin
    // uuid 必须是小写
    public static final String SERVICE_UUID = "aec91000-6e7a-4bc2-9a4c-4cda7a728f58";  //蓝牙通讯服务
    public static final String CONFIG_UUID = "aec91001-6e7a-4bc2-9a4c-4cda7a728f58";  //写特征
    public static final String READ_UUID = "aec91002-6e7a-4bc2-9a4c-4cda7a728f58";  //读特征
    public static final String STATUS_UUID = "aec91003-6e7a-4bc2-9a4c-4cda7a728f58";  //电池特征

    private ImageView dev_iv_back, dev_iv_scan;
    private RecyclerView dev_rv;
    private Button dev_btn_next;
    private TextView dev_tv_hint;
    private LoadingDialog loadingDialog;

    private DeviceAdapter deviceAdapter;
    private List<SensorInfo> deviceBeanList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);

        initPermission();

        if (!checkBluetoothStatus())
            return;

        showInitDialog();
    }


    @Override
    protected void onDestroy() {
        presenter.unbindFromService();
        presenter.stopService();
        super.onDestroy();
    }


    @Override
    protected int initLayout() {
        return R.layout.activity_device;
    }

    /**
     * 初始化视图
     */
    @Override
    protected boolean initView() {
        dev_iv_back = findViewById(R.id.dev_iv_back);
        dev_iv_back.setOnClickListener(v -> {
            if(presenter.getConnectedSensorsSize() > 0) {
                showExitDialog();
            }else{
                AppManager.getInstance().finishActivity();
            }
        });

        dev_iv_scan = findViewById(R.id.dev_iv_scan);
        dev_iv_scan.setOnClickListener(v -> {
            if (presenter.isDiscovering()) {
                presenter.stopDiscovering();
            } else {
                presenter.startDiscovering();
            }
        });

        dev_rv = findViewById(R.id.dev_rv);

        dev_tv_hint = findViewById(R.id.dev_tv_hint);
        dev_tv_hint.setText(R.string.text_no_sensor_zerolab);

        dev_btn_next = findViewById(R.id.dev_btn_next);
        dev_btn_next.setOnClickListener(v -> {
            if (presenter.getConnectedSensorsSize() == 0) {
                showErrorDialog("当前尚未连接设备");
                return;
            }
            startActivity(new Intent(ZeroLabDeviceActivity.this, ZeroLabSensorActivity.class));
        });


        dev_tv_hint = findViewById(R.id.dev_tv_hint);
        PressUtil.setPressChange(ZeroLabDeviceActivity.this, dev_iv_back, dev_iv_scan);

        return true;
    }


    /**
     * 初始化数据
     */
    @Override
    protected boolean initData() {
        deviceBeanList = new ArrayList<>();
        deviceAdapter = new DeviceAdapter(R.layout.item_device, deviceBeanList,
                (view, sensorInfo) -> {
                    CheckBox checkBox = (CheckBox) view;
                    if (checkBox.isChecked()) {
                        ToastUtil.show("正在连接...");
                        presenter.connectSensor(sensorInfo.getAddress(), new Callback() {
                            @Override
                            public void onSuccess(String message, String data) {
                                refreshSensorList();
                                showHintDialog("当前已连接" + presenter.getConnectedSensorsSize() + "个设备");
                            }

                            @Override
                            public void onFail(String message, String data) {
                                showErrorDialog(message + "\n" + data);
                            }

                            @Override
                            public void onError(String message, String data) {
                                showErrorDialog(message + "\n" + data);
                            }
                        });
                    } else {
                        ToastUtil.show("正在断开...");
                        presenter.disconnectSensor(sensorInfo.getAddress(), new Callback() {
                            @Override
                            public void onSuccess(String message, String data) {
                                refreshSensorList();
                            }

                            @Override
                            public void onFail(String message, String data) {
                                checkBox.setChecked(false);
                                showErrorDialog(message + "\n" + data);
                            }

                            @Override
                            public void onError(String message, String data) {
                                checkBox.setChecked(false);
                                showErrorDialog(message + "\n" + data);
                            }
                        });
                    }
                });

        dev_rv.setLayoutManager(new LinearLayoutManager(this));
        LinearSnapHelper snapHelper = new LinearSnapHelper();
        snapHelper.attachToRecyclerView(dev_rv);
        dev_rv.setAdapter(deviceAdapter);

        return true;
    }

    @Override
    protected ZeroLabDevicePresenter genPresenter() {
        return new ZeroLabDevicePresenter(this);
    }


    /**
     * 初始化权限
     */
    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {// Android 12 及以上版本
            perms = new String[]{
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_ADVERTISE
            };
        } else {
            perms = new String[]{
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN
            };
        }

        perms = concat(perms, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION});

        if (!EasyPermissions.hasPermissions(this, perms))
            EasyPermissions.requestPermissions(this, "请授予APP蓝牙、位置、存储等权限，以实现连接蓝牙设备和存储数据功能。",
                    RC_PERMISSION, perms);
    }

    // 合并数组的辅助方法
    private String[] concat(String[] first, String[] second) {
        String[] result = new String[first.length + second.length];
        System.arraycopy(first, 0, result, 0, first.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTION_REQUEST_ENABLE) {
            presenter.startOrBindToService();
            LogUtil.d("startOrBindToService");
        } else if (requestCode == RESULT_CANCELED) {
            dismissInitDialog();
            showErrorDialog("蓝牙未成功开启");
        }

        if (requestCode == APP_SETTINGS_REQ_CODE) {
            // 从设置页面返回，重新检查权限
            if (EasyPermissions.hasPermissions(this, perms)) {
                presenter.startOrBindToService();
            } else {
                ToastUtil.show("权限未开启，无法使用蓝牙功能");
                AppManager.getInstance().finishActivity();
            }
        }
    }



    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == RC_PERMISSION) { // 检查是否所有必要权限都已获取
            if (EasyPermissions.hasPermissions(this, this.perms)) {
                presenter.startOrBindToService();
            } else { // 可能只获取了部分权限，重新检查和申请
                initPermission();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == RC_PERMISSION) {
            if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                // 用户永久拒绝了某些权限，弹出对话框引导用户去设置页面
                ToastUtil.show("必要权限被永久拒绝，请前往设置页面手动开启，否则无法正常使用蓝牙功能");
                Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, APP_SETTINGS_REQ_CODE);
            } else { // 用户拒绝了权限，但没有勾选"不再询问"
                new HintDialog(this).showDialog(
                        this,
                        "权限申请",
                        "没有必要权限将无法使用蓝牙功能，是否重新申请权限？",
                        view -> initPermission(), // 重新申请权限
                        view -> AppManager.getInstance().finishActivity()// 用户不想授权，退出应用
                );
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onScanStatusEvent(ScanStatusEvent event) {
        switch (event.getStatus()) {
            case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                ToastUtil.show("扫描中…");
                LogUtil.d("ACTION_DISCOVERY_STARTED");
                break;

            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                ToastUtil.show("扫描完成");
                LogUtil.d("ACTION_DISCOVERY_FINISHED");
                break;

            case "DISCOVERY_DEVICE":
                refreshSensorList();
                break;

            case "CONNECT_FAILURE": //连接失败
                Log.d(TAG, "连接失败");
                ToastUtil.show("连接失败");
                refreshSensorList();
                break;

            case "CONNECT_SUCCESS":  //连接成功
                Log.d(TAG, "连接成功");
                ToastUtil.show("连接成功");
                refreshSensorList();
                break;

            case "BT_CLOSED":
                Log.d(TAG, "系统蓝牙已关闭");
                ToastUtil.show("系统蓝牙已关闭");
                break;

            case "BT_OPENED":
                Log.d(TAG, "系统蓝牙已打开");
                break;
        }
    }


    private void refreshSensorList() {
        runOnUiThread(() -> {
            deviceBeanList.clear();
            deviceBeanList.addAll(presenter.getSensorInfoList());
            deviceAdapter.notifyDataSetChanged();
            if (deviceBeanList.size() > 0)
                dev_tv_hint.setVisibility(View.INVISIBLE);
        });
    }


    @Override
    public void onBackPressed() {
        if(presenter.getConnectedSensorsSize() > 0) {
            showExitDialog();
        }else{
            super.onBackPressed();
        }
    }


    public void showInitDialog() {
        loadingDialog = new LoadingDialog(ZeroLabDeviceActivity.this);
        loadingDialog.showDialog(ZeroLabDeviceActivity.this, "正在准备，请稍后…");
    }


    public void dismissInitDialog() {
        if (loadingDialog != null && loadingDialog.isShowing())
            loadingDialog.dismiss();
    }


    private void showExitDialog() {
        LogUtil.w("showExitDialog");
        HintDialog hintDialog = new HintDialog(this);
        hintDialog.showDialog(this, "提示", "确定断开所有连接并退出？",
                view -> {
                    if(presenter != null)
                        presenter.disconnectAllSensor();
                    hintDialog.dismiss();
                    AppManager.getInstance().finishActivity();
                }, view -> hintDialog.dismiss());
    }


    private boolean checkBluetoothStatus() {
        if (!EasyPermissions.hasPermissions(this, perms)) {
            ToastUtil.show("请授予蓝牙和位置权限");
            return false;
        }

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
            showErrorDialog("本机没有找到蓝牙硬件或驱动！");
            dev_tv_hint.setVisibility(View.VISIBLE);
            return false;
        }

        if (!adapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, ACTION_REQUEST_ENABLE);
        } else {
            presenter.startOrBindToService();
        }

        return true;
    }
}
